package com.yh.serviceimpl;
import com.yh.javabean.Permission;
import com.yh.javabean.Users;
import com.yh.mapper.PermissionMapper;
import com.yh.mapper.UsersMapper;
import com.yh.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
 * @Auther: als
 * @Date: 2024/6/1 - 06 - 01 - 11:36
 * @Description: com.yh.serviceimpl
 * @version: 1.0
 */
@Service("usersService")
public class UsersServiceImpl implements UsersService {

    @Autowired
    UsersMapper usersMapper;
    @Autowired
    PermissionMapper permissionMapper;

    @Autowired(required = false)
    BCryptPasswordEncoder passwordEncoder;


    //如果没有查询到对应数据 返回null
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询数据返回实体类对应数据
        Users users = usersMapper.selectByUserName(username);
        if(users!=null){
            User user = new User(users.getUsername(),
                    users.getPassword(),
                    users.getStatus() != 0 ,
                    true,true,true,
                    getAuthority(users.getId()));
            return user;
        }else {
            return null;
        }
    }

    public Set<GrantedAuthority> getAuthority(int uid){
        Set<GrantedAuthority> simpleGrantedAuthorities = new HashSet<>();
        List<Permission> list = permissionMapper.selectByUid(uid);
        if(list!=null){
            for (Permission permission : list) {
                simpleGrantedAuthorities.add(new SimpleGrantedAuthority(permission.getPermissionName()));
            }
        }
        return  simpleGrantedAuthorities;
    }




}
